<template>
  <div ref="chartDom" style="height: 400px;"></div>
</template>

<script>
import echarts from "echarts/lib/echarts";
import "echarts/lib/chart/bar";
import "echarts/lib/component/title";
import "echarts/lib/component/tooltip";
import { addListener, removeListener } from "resize-detector"; // 监听容器大小变化
import debounce from "lodash/debounce"; // 防抖
export default {
  name: "Chart",
  props: {
    chartOption: {
      type: Object,
      default: () => ({}),
      required: true
    }
  },
  data() {
    return {};
  },
  watch: {
    // 深度监听
    // chartOption:{
    //     handler(newOption){
    //         this.chart.setOption(newOption)
    //     },
    //     deep:true
    // },
    // 普通监听
    chartOption(newOption) {
      this.chart.setOption(newOption);
    }
  },
  mounted() {
    this.renderChart();
  },
  beforeDestroy() {
    removeListener(this.$refs.chartDom, this.resize);
  },
  methods: {
    renderChart() {
      this.chart = echarts.init(this.$refs.chartDom);
      addListener(this.$refs.chartDom, debounce(this.resize, 300));
      this.chart.setOption(this.chartOption);
    },
    resize() {
      console.info("chart resize");
      this.chart.resize();
    }
  }
};
</script>

<style lang="less"></style>
